package im

import (
    "encoding/xml"
	"io"
	//"bytes"
    //"strconv"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"wxsdk/miniapp/utils/security"
	//"wxsdk/miniapp/message/callback/response"
	"dhfshop/domain/im"
)

type MsgHandleController struct {
	base.BaseController
}

//公众号消息与事件接收服务，对应审核资料中公众号消息与事件接收URL
func (this *MsgHandleController) AcceptMessageAndEvent() {
	isvToken := beego.AppConfig.String("IsvToken")
	isvAESKey := beego.AppConfig.String("IsvAESKey")
	isvAppId := beego.AppConfig.String("IsvAppId")
	method := this.Ctx.Request.Method
	switch method {
	case "POST": // 消息处理
		appId := this.GetString(":appid")
		timestamp := this.GetString("timestamp")
		nonce := this.GetString("nonce")
		msgSignature := this.GetString("msg_signature")
		if timestamp == "" || nonce == "" || msgSignature == "" {
			this.Ctx.WriteString("parameter is fail")
		}
		reqMap, err := security.DecrypterXmlToMap(isvToken,isvAESKey,isvAppId,timestamp,nonce,msgSignature,this.Ctx.Input.RequestBody)
		if err != nil {
		    beego.Emergency("DecrypterXmlToMap error: " + err.Error())
		    return
		}
		// 自动化测试的专用测试公众号
		if appId == "wx570bc396a51b8ff8" {
			AutoReplyWholeTest(isvToken,isvAESKey,isvAppId,reqMap,&this.Controller)
			return
		}
		// 自动化测试的专用测试小程序
		if appId == "wxd101a85aa106f53e" {
			return
		}
		reqMap["AppId"] =  appId
		reqMap["LocalKind"] =  "COMMON_MESSAGE"
		imlayer.PushMsgSvrIns.PushDao <- &reqMap
		//客服消息转发
		/*
		if reqMap["MsgType"] != "event" {
		    wxCreateTime, _:= strconv.ParseInt(reqMap["CreateTime"], 10, 64)
			resp := response.NewTransferToCustomerService(reqMap["FromUserName"],reqMap["ToUserName"],wxCreateTime,"")
	        // 明文回复
			XmlEncodeResponseMessage(this.Ctx.ResponseWriter, resp)
			buffer := new(bytes.Buffer)
			XmlEncodeResponseMessage(buffer, resp)
			beego.Debug("XmlEncodeResponseMessage:", string(buffer.Bytes()))
		}else{ */
		    this.Ctx.Output.Body([]byte("success"))
		//}
		return
	case "GET": // 首次验证
		FirstVerifyTest(&this.Controller)
	}
}

func XmlEncodeResponseMessage(w io.Writer, msg interface{}) error {
	return xml.NewEncoder(w).Encode(msg)
}
